<template>
  <div class="userCenter addressBox">
    <form name="userForm" class="userForm" ref="userForm">
      <div class="list ">
        <div class="item">
          <div>
            <div class="item-content item-content-result">
              <span class="item-content-label"> 收货人姓名： </span>
              <input v-model.trim="address.name" placeholder="请输入收货人姓名" ref="receiver" class="item-result" required>
            </div>
          </div>
        </div>
      </div>
      <div class="list ">
        <div class="item">
          <div>
            <div class="item-content item-content-result">
              <span class="item-content-label"> 手机号码： </span>
              <input v-model.trim="address.mobile" placeholder="请输入手机号码" ref="tel" class="item-result" required
                     pattern="(1[3|4|5|6|7|8|9])\d{9}">
            </div>
          </div>
        </div>
      </div>
      <div class="list ">
        <div class="item">
          <div>
            <div class="item-content item-content-result">
              <span class="item-content-label"> 所在地区： </span>
              <div style="position:relative">
                <input v-model="locationArea" placeholder="" ref="area" class="item-result" required
                       @click="showAreaDialog($event)">
              </div>

            </div>
          </div>
        </div>
      </div>

      <div class="list detailList">
        <div class="item">
          <div>
            <div class="item-content item-content-result">
              <span class="item-content-label"> 详细地址： </span>
              <textarea class="" v-model="address.addr" ref="detail" placeholder="请输入详细地址"></textarea>
            </div>
          </div>
        </div>
      </div>

    </form>
    <div class="buttonslist">
      <span class="confirm" v-if="isEdit" @click="edit()">修改</span>
      <span class="confirm" v-if="!isEdit" @click="saveBase($event)">保存</span>
      <span class="cancel  drawer-closer" @click="cancel()">取消</span>
    </div>
    <!--省市区-->
    <div>
      <v-area :isshow="isShow" :pCode="address.privinceId" :cCode="address.cityId" :dCode="address.townId"
              v-on:fadeAddress="hideAreaDialog"></v-area>
    </div>

    <v-loading :showLoading="showLoading"></v-loading>
  </div>
</template>
<script>
  import {AlertDialog, confirmDialog, checkLen, getLocalstorage} from '../../common/js/common'
  import AreaComp from '../area/index'
  import {HttpRequest} from '../../common/js/httpFun'
  import {linklist} from '../../common/js/mockdata'
  import Loading from '../loading/index'
  export default ({
    props: {},
    data () {
      return {
        'isEdit': true,
        'isShow': false,
        'locationArea': '',
        'showLoading': false,
        'address': {
          'name': '',
          'mobile': '',
          'province': '',
          'privinceId': '440000',
          'city': '',
          'cityId': '440100',
          'town': '',
          'townId': '440106',
          'addr': ''
        },
        'initAddress': {
          'name': '',
          'mobile': '',
          'province': '',
          'privinceId': '',
          'city': '',
          'cityId': '',
          'town': '',
          'townId': '',
          'addr': ''
        },
        'initLocationArea': '',
        'inputeles': null,
        'textele': null
      }
    },
    created () {
      console.log('111111111111111111', this.address)
    },
    mounted () {
      this.inputeles = this.$refs.userForm.querySelectorAll('input')
      this.textele = this.$refs.userForm.querySelector('textarea')
      this.fetchData()
    },
    computed: {},
    methods: {
      createToast (text) {
        AlertDialog('警告', text)
      },
      fetchData () {
        // 获取用户地址信息
        let userInfo = getLocalstorage('userInfo')
        let param = {id: userInfo.userId}
        let result = HttpRequest(linklist.addressUrl, param)
        result.then((response) => {
          let body = response.body
          if (body.code === 0) {
            let addr = body.data
            this.address = (addr && addr.length > 0) ? addr[0] : this.address
            this.address = Object.assign(this.address, {addrId: this.address.id})
            this.initAddress = JSON.stringify(this.address)
            console.log('testgggggggg', this.address)
            this.initData()
          }
          else {
            AlertDialog('提示', body.msg)
          }
        }, (response) => {
          AlertDialog('提示', '获取列表失败，请稍后再试', '确定', true)
        }).catch((response) => {
          AlertDialog('提示', '获取用户信息失败，请稍后再试', '确定', true)
        })
      },
      createConfirmDialog (msg, yesFun, noFun) {
        confirmDialog(msg, yesFun, noFun)
      },
      initData () {
        /* 判断用户是否可编辑地址信息 */
        if (this.address && this.address.name) {
          for (let value of this.inputeles) {
            value.setAttribute('disabled', true)
          }
          this.textele.setAttribute('disabled', true)
          this.isEdit = true
        }
        else {
          this.edit()
        }
      },
      edit () {
        for (let value of this.inputeles) {
          value.removeAttribute('disabled', true)
        }
        this.textele.removeAttribute('disabled', true)
        this.isEdit = false
      },
      saveBase (event) {
        event.preventDefault()
        event.stopPropagation()
        // 验证规则
        if (!this.address.name) {
          this.createToast('请填写收货人信息')
          return false
        }
        else {
          if (checkLen(this.address.name) > 10) {
            this.createToast('最多输入20个字符')
            return false
          }
        }
        if (this.$refs.tel.validity.valueMissing) {
          this.createToast('请填写手机号')
          return false
        }
        else {
          if (!this.$refs.tel.validity.valid) {
            this.createToast('请填写正确的手机号')
            return false
          }
        }
        if (!this.address.addr) {
          this.createToast('请填写详细地址')
          return false
        }
        else {
          if (checkLen(this.address.addr) > 100) {
            this.createToast('详细地址最多输入100个字符')
            return false
          }
        }
        this.createConfirmDialog('确定修改收货地址吗?',
          () => {
            this.saveData()
          },
          () => {
          }
        )
      },
      saveData () {
        let _self = this
        this.showLoading = true
        let result = HttpRequest(linklist.addAddress, this.address, 2)
        result.then((response) => {
          let body = response.body
          this.showLoading = false
          if (body.code === 0) {
            _self.address = Object.assign(_self.address, {addrId: _self.address.id})
            _self.initAddress = JSON.stringify(_self.address)
            _self.initLocationArea = _self.locationArea
            _self.initData()
            _self.$emit('closeDrawer')
          }
          else {
            AlertDialog('提示', body.msg)
          }
        }, (response) => {
          this.showLoading = false
          AlertDialog('提示', '保存地址失败，请稍后再试')
        }).catch((response) => {
          this.showLoading = false
          AlertDialog('提示', '保存地址失败，请稍后再试')
        })
      },
      cancel () {
        // 取消编辑地址信息
        this.backToInitial()
        this.$emit('closeDrawer')
      },
      backToInitial () {
        // 初始化所有的值
        this.address = Object.assign({}, JSON.parse(this.initAddress))
        this.locationArea = this.initLocationArea
        this.initData()
      },
      showAreaDialog (event) {
        /* 显示省市区弹框 */
        this.isShow = !this.isShow
      },
      hideAreaDialog () {
        /* 关闭省市区弹框 */
        this.isShow = false
        // console.log('arguments', arguments)
        if (arguments) {
          this.locationArea = arguments[0].name + ' ' + arguments[1].name + ' ' + arguments[2].name
          this.address.provinceId = arguments[0].code
          this.address.cityId = arguments[1].code
          this.address.townId = arguments[2].code
          this.address.province = arguments[0].name
          this.address.city = arguments[1].name
          this.address.town = arguments[2].name
          if (arguments[3] === 1) {
            this.initLocationArea = this.locationArea
          }
        }
      }
    },
    components: {
      'v-area': AreaComp,
      'v-loading': Loading
    }
  })
</script>
<style lang="stylus" rel="stylesheet/stylus">
  @import "../../common/stylus/redifined.styl"
  @import "./index.styl"
  .addressBox
    position fixed
    min-height 100vh
    overflow-y scroll
    width 100%
    left 0
    right 0
    background bgColor
    z-index 2
    .item
      & > div
        flex 1 1 auto
        .item-content
          & > div, & > input, & > textarea
            flex 1 1 auto
</style>
